import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpServer {
    private ServerSocket socket = null;
    Map<String,String> map;
    public TcpServer(int port) throws IOException {
        socket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        ExecutorService executorService = Executors.newCachedThreadPool();
        while(true){//每循环一次都会创建一个Socket，就会导致文件资源泄露
            Socket clientSocket = socket.accept();
            /*Thread t = new Thread(()->{
                try {
                    processConnection(clientSocket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
            t.start();*/
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processConnection(clientSocket);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    }
    public void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("[%s:%d],客户端上线\n",clientSocket.getInetAddress(),clientSocket.getPort());
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
            while(true){
                Scanner scanner = new Scanner(inputStream);
                if(!scanner.hasNext()){
                    System.out.println("客户端下线");
                    break;
                }
                //1.读取请求
                // next()读到空白符就停止
                String req = scanner.next();
                //2.计算响应
                String res = process(req);
                //3.返回响应
                PrintWriter writer = new PrintWriter(outputStream);
                writer.println(res);
                writer.flush();
                System.out.printf("[%s:%d] req=%s, res=%s\n",clientSocket.getInetAddress(),
                        clientSocket.getPort(),req,res);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            clientSocket.close();
        }
    }
    public String process(String req){
        return req;
    }

    public static void main(String[] args) throws IOException {
        TcpServer server = new TcpServer(9090);
        server.start();
    }
}














